﻿using LJ.EventBus.FastDog.Data;
using LJ.EventBus.FastDog.Transport.Abstractions;
using LJ.FaultHandler.Abstractions;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJ.EventBus.FastDog.Internal;

public class MessageListener(IFaultHandlerFactory faultHandlerFactory, IEventHandlerInvoker eventHandlerInvoker, ILogger<MessageListener> logger) : IMessageListener
{
    private readonly IFaultHandlerFactory _faultHandlerFactory = faultHandlerFactory;
    private readonly IEventHandlerInvoker _eventHandlerInvoker = eventHandlerInvoker;
    private readonly ILogger _logger = logger;

    public async Task<MessageReceiveResult> OnReceiveAsync(Message message, CancellationToken cancellationToken)
    {
		try
		{
            var faultHandler = _faultHandlerFactory.Create();
            await faultHandler.ExecuteAsync(async a => {

                await _eventHandlerInvoker.InvokeAsync(message);

            }, cancellationToken);

            return MessageReceiveResult.Success;
        }
		catch (Exception ex)
		{
            _logger.LogWarning("[EventBus] MessageListener  {message}", ex.Message);

            return MessageReceiveResult.Failed;
        }
    }


}
